<template>
  <van-nav-bar :title="t('refund.title')" left-arrow @click-left="onClickLeft" placeholder fixed />
  <van-row>
    <van-col span="24">
      <van-field ref="orderNoRef" v-model="returnNo" size="large" @keydown.enter="handleScan" @clear="reScan" :placeholder="t('refund.pleaseScanningOrderOrSkuNo')" clearable>
        <template #left-icon>
          <van-icon name="enlarge" size="1.5rem" class="px-2"/>
        </template>
      </van-field>
    </van-col>
  </van-row>
  <van-cell-group v-if="showSn === 1">
    <van-empty v-if="finished && orderList?.length <= 0" :description="t('noData')"/>
    <van-list v-else v-model:loading="loading" :finished="finished" :loading-text="t('loading')" :finished-text="t('noMoreData')" @load="onLoad" >
      <van-row class="p-5 van-hairline--surround" v-for="(item, i) in orderList" :key="i" @click="choose(item.returnNo)">
        <van-col>{{ t('refund.returnNo') + item.returnNo }}</van-col>
      </van-row>
    </van-list>
  </van-cell-group>
  <div v-else>
    <div v-if="outboundList?.length > 0">
      <van-row class="px-5 py-2">
        <van-col>{{ t('refund.referOutboundOrder') }}</van-col>
      </van-row>
      <van-cell-group>
        <van-row class="p-5 van-hairline--surround" v-for="(item, i) in outboundList" :key="i" @click="showAddRefund(item)">
          <van-col>{{ t('refund.outboundNo') + item.orderNo }}</van-col>
        </van-row>
      </van-cell-group>
    </div>
    <div v-if="returnNoList?.length > 0 || outboundList?.length <= 0">
      <van-row class="px-5 py-2">
        <van-col>{{ t('refund.referRefundOrder') }}</van-col>
      </van-row>
      <van-cell-group>
        <van-empty v-if="returnNoList?.length <= 0" :description="t('noData')"/>
        <van-row class="p-5 van-hairline--surround" v-for="(item, i) in returnNoList" :key="i" @click="choose(item)">
          <van-col>{{ t('refund.returnNo') + item }}</van-col>
        </van-row>
      </van-cell-group>
    </div>
    <van-action-bar placeholder>
      <van-row class="w-full p-1">
        <van-col span="24">
          <van-button class="text-base" block type="primary" @click="toOwnerless">{{ t('refund.ownerlessRegister') }}</van-button>
        </van-col>
      </van-row>
    </van-action-bar>
  </div>
  <van-back-top />

  <van-action-sheet v-model:show="showAction" :title="t('refund.addRefundOrder')">
    <van-cell-group class="h-full mx-5">
      <van-field v-model="returnOrder.returnTypeName" is-link readonly required :label="t('refund.refundType')" name="refundType" @click="showReturnType = true" />
      <van-field v-model="returnOrder.returnNo" required clearable :label="t('refund.refundNo')" name="refundNo" />
      <div class="max-h-60 overflow-x-auto">
        <van-swipe-cell v-for="(sku, i) in returnOrder.orderSkuBOList" :key="i" class="my-2">
          <van-cell :title="'SKU:' + sku.skuCode" />
          <template v-if="returnOrder.orderSkuBOList.length > 1"  #right>
            <div class="pl-2">
              <van-button type="danger" icon="delete" @click="returnOrder.orderSkuBOList.splice(i, 1)" />
            </div>
          </template>
        </van-swipe-cell>
      </div>
    </van-cell-group>
    <div class="p-2">
      <van-button :loading="confirmLoading" block type="primary" @click="submitRefund">
        {{ t('confirm') }}
      </van-button>
    </div>
  </van-action-sheet>
  <van-popup v-model:show="showReturnType" position="bottom">
    <van-picker :confirm-button-text="t('confirm')" :cancel-button-text="t('cancel')" :columns="returnTypeEnums" @confirm="selectReturnType" @cancel="showReturnType = false" />
  </van-popup>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { postRequest, scanFail, scanSuccess } from "@/api";
import router from "@/router";
import { nextTick } from "vue";
import { AppToast } from "@/utils/appToast";

const { t } = useI18n();
const onClickLeft = () => {
  showSn.value -= 1
  nextTick(() => orderNoRef.value.focus())
  if(!showSn.value) {
    history.back();
  }
}

const showSn = ref(1);
const orderList = ref([]);
const loading = ref(false);
const confirmLoading = ref(false);
const showReturnType = ref(false);
const finished = ref(false);
const showAction = ref(false);
const pageNo = ref(0);
const returnNo = ref();
const orderNoRef = ref();
const returnNoList = ref([]);
const outboundList = ref([]);
const returnOrder: any = ref({});

onMounted(() => {
  orderNoRef.value.focus()
});

const returnTypeEnums = [
  { text: t('enums.returnType.buyer'), value: 1 },
  { text: t('enums.returnType.provider'), value: 2 },
  { text: t('enums.returnType.claim'), value: 3 }
];

const reScan = () => {
  showSn.value = 1;
  returnNo.value = null;
  returnNoList.value = []
  outboundList.value = []
};

const onLoad = () => {
  pageNo.value += 1;
  postRequest("/inbound/getReturnEnterPageList", { pageSize: 20, pageNo: pageNo.value }).then(res => {
    if (res.data.returnNoRespList?.length > 0) {
      orderList.value = orderList.value.concat(res.data.returnNoRespList)
    } else {
      finished.value = true;
    }
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    finished.value = true;
  })
};

const handleScan = () => {
  postRequest("/outbound/outBoundOrder/queryOutboundOrderPageList", { providerTrackingNo: returnNo.value }).then(res => {
    postRequest("/inbound/getReturnEnterByNo", { number: returnNo.value }).then(res => {
      scanSuccess();
      if (res.data.returnNoList) {
        returnNoList.value = res.data.returnNoList
        showSn.value = 2
      } else {
        router.push({
          name: 'RefundOperate',
          query: {
            returnNo: res.data.returnNo,
          }
        });
      }
    }).catch(() => {
      scanFail();
    })
    outboundList.value = res.data.dataList || []
  })
};

const selectReturnType = ({ selectedOptions }) => {
  returnOrder.value.returnType = selectedOptions[0]?.value;
  returnOrder.value.returnTypeName = selectedOptions[0]?.text;
  showReturnType.value = false;
};

const showAddRefund = (order) => {
  returnOrder.value = {
    receiptDepotId: order.depotId,
    providerTrackingNo: order.providerTrackingNo,
    returnNo: order.providerTrackingNo,
    outboundNo: order.orderNo,
    customId: order.customerId,
    orderSkuBOList: order.goodsList?.map(item => {
      return {
        skuCode: item.goodsSkuCode,
        skuNum: item.goodsQuantity
      }
    }),
  }
  showAction.value = true
}

const validateReturn = () => {
  return returnOrder.value.returnNo && returnOrder.value.returnType
}


const submitRefund = () => {
  confirmLoading.value = true
  if (!validateReturn()) {
    AppToast(t("pleaseCheckRequired"), "danger", true);
    confirmLoading.value = false
    return
  }
  postRequest('/inbound/add', returnOrder.value).then((res) => {
    AppToast(t("refund.addRefundOrderSuccess"), "success")
    router.push({
      name: 'RefundOperate',
      query: {
        returnNo: res.data
      }
    });
  }).finally(() => {
    confirmLoading.value = false
  })
}

const choose = (returnNo) => {
  router.push({
    name: 'RefundOperate',
    query: {
      returnNo
    }
  });
}
const toOwnerless = () => {
  router.push({
    name: 'Ownerless',
    query: {
      returnNo: returnNo.value
    }
  });
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}
</style>
